package com.suixin.learn.persistence.config;

import com.suixin.learn.persistence.pojo.Configuration;
import com.suixin.learn.persistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
    private Configuration configuration;
    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {

        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(in);
        Element root = read.getRootElement();
        String namespace = root.attributeValue("namespace");
        getSqlNode(root, namespace,"select");
        getSqlNode(root, namespace,"update");
        getSqlNode(root, namespace,"delete");
        getSqlNode(root, namespace,"insert");
    }

    private void getSqlNode(Element root, String namespace,String node) {
        List<Element> list = root.selectNodes("//"+node);
        for(Element ele : list){

            String id = ele.attributeValue("id");
            String parameterType = ele.attributeValue("parameterType");
            String resultType = ele.attributeValue("resultType");
            String sql = ele.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setCommandType(node);
            mappedStatement.setNameSpace(namespace);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlId(id);

            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);

        }
    }
}
